﻿namespace EasyWeb.Web.UI
{
    using System.Collections.Generic;
    using System.IO;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using System.Web.UI;

    public abstract class EWViewComponent
    {
        private string name;

        protected EWViewComponent(ViewContext viewContext)
        {
            EWGuard.IsNotNull(viewContext, "viewContext");

            this.ViewContext = viewContext;
            this.HtmlAttributes = new RouteValueDictionary();
        }

        public string Name
        {
            get { return this.name; }
            set
            {
                EWGuard.IsNotNullOrEmpty(value, "value");
                this.name = value;
            }
        }

        public string Id
        {
            get { return this.HtmlAttributes.ContainsKey("id") ? this.HtmlAttributes["id"].ToString() : this.Name; }
        }

        public IDictionary<string, object> HtmlAttributes { get; private set; }

        public ViewContext ViewContext { get; private set; }

        public void Render()
        {
            using (var writer = new HtmlTextWriter(this.ViewContext.Writer))
            {
                WriteHtml(writer);
            }
        }

        public IHtmlString ToHtmlString()
        {
            var output = new StringWriter();

            using (var writer = new HtmlTextWriter(output))
            {
                WriteHtml(writer);
                return MvcHtmlString.Create(output.ToString());
            }
        }

        public override string ToString()
        {
            return ToHtmlString().ToHtmlString();
        }

        protected abstract void WriteHtml(HtmlTextWriter writer);
    }
}
